package com.yuxl.ai.knowledgeText.repository;

import com.yuxl.ai.knowledgeText.domain.AiKnowledgeTextEmbeddingQuery;
import com.yuxl.ai.knowledgeText.domain.AiKnowledgeTextEmbeddingRes;
import com.yuxl.ai.knowledgeText.entity.AiKnowledgeTextEmbedding;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import com.yuxl.common.core.annotation.PostgreSqlRepository;
import reactor.core.publisher.Flux;

@PostgreSqlRepository
public interface AiKnowledgeTextEmbeddingRepository extends ReactiveCrudRepository<AiKnowledgeTextEmbedding, Long> {


    @Query("""
                SELECT * 
                FROM (SELECT name, text_id, knowledge_id, content, 1 - (embedding <=> :embedding::vector) AS similarity FROM ai_knowledge_text_embedding) t
                WHERE (:#{#query.content} IS NULL OR t.content LIKE CONCAT('%', :#{#query.content}, '%'))
                AND t.similarity > :#{#query.similarity}
                ORDER BY t.similarity DESC
                LIMIT :#{#query.limit}
            """)
    Flux<AiKnowledgeTextEmbeddingRes> query(AiKnowledgeTextEmbeddingQuery query, String embedding);
}
